# -*- coding: utf-8 -*-
# @Time    : 2024/05/08 13:43
# @Author  : Mr.su
# @FileName: fendi.py
# @FileDesc:
from CollectSpiders.spiders.configs.fendi_config import config_dic
from CollectSpiders.settings import LOG_FILE_PATH
from CollectSpiders.toots.methods import make_md5
from CollectSpiders.toots.connects import RedisClient
import scrapy, json, datetime, urllib.parse, logging, re


# noinspection PyAbstractClass,PyMethodMayBeStatic
class CrawlSpider(scrapy.Spider):
    name, domain = 'fendi', 'www.fendi.com'
    redisClient = RedisClient()
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    }
    custom_settings = {
        'CONCURRENT_REQUESTS': 2,
        'LOG_FILE': LOG_FILE_PATH, 'LOG_LEVEL': 'WARNING'
    }

    def __init__(self, data=None, *args, **kwargs):
        """
        传入自定义参数
        :param data: 数据列表
        :param args:
        :param kwargs:
        """
        super(CrawlSpider, self).__init__(*args, **kwargs)
        self.data = json.loads(urllib.parse.unquote(data)) if data else {
            "pid": "1800", "status": 1, "wait_time": 3600, "brand": "fendi",
            "childs": {
                "1801": {
                    "sid": "1801", "label": "女士-新款上市", "upload": 1, "status": 1, "webtype": "taobao",
                    "url": "https://www.fendi.cn/man/featured/new.html"
                }
            }
        }

    def start_requests(self):
        column = list(self.data['childs'].values())[0]
        url = 'https://www.fendi.cn/rest/default/V2/applet/products/?isQuickDelivery=false&catId={}&sortDir=asc&page={}&pageSize=20&sort=position'
        if column['status'] == 1:
            for key, value in config_dic.items():
                if key in column['url']:
                    cat_id = value['_id']
                    yield scrapy.Request(
                        url.format(cat_id, 1), headers=self.headers, callback=self.process_lis,
                        meta={'url': url, 'pg': 1, 'cat_id': cat_id}
                    )

    def process_lis(self, response):
        column = list(self.data['childs'].values())[0]
        js = json.loads(response.text)
        has_more = True
        for item in js['data']['items']:
            result = self.redisClient.conn.sadd('products', make_md5(item['url']))
            if not result:
                has_more = False
                break
            product = {
                '_id': '',
                'pid': self.data['pid'],
                'sid': column['sid'],
                'status': '0',  # 0:未下载  1:已下载  6:下载失败
                'webtype': column['webtype'],
                'url': item['url'],
                'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'brand': self.data['brand'],
                'image': '',
                'domain': self.domain,
                'label': column['label'],
                'upload': column['upload'],
                'name': item['shortDesc']
            }
            detail_url = 'https://www.fendi.cn/rest/default/V1/applet/product/{}'.format(item['sku'])
            yield scrapy.Request(
                detail_url, headers=self.headers, callback=self.process_detail,
                meta={'product': product}
            )
        pg_count = js['data']['totalPages']
        pg = response.meta['pg']
        if has_more and pg < pg_count:
            pg = pg + 1
            url = response.meta['url']
            cat_id = response.meta['cat_id']
            yield scrapy.Request(
                url.format(cat_id, pg), headers=self.headers, callback=self.process_lis,
                meta={'url': url, 'pg': pg, 'cat_id': cat_id}
            )

    def process_detail(self, response):
        product = response.meta['product']
        js = json.loads(response.text)
        img_lis = [img['big_url'] for img in js['data']['images']]
        product['_id'] = make_md5(img_lis[0])
        product['image'] = img_lis
        logging.warning('<{}>: 数据id: {}'.format(self.domain, product['_id']))
        yield product
